package com.bp.village.project.controller;

import java.util.*;

import com.bp.common.constant.Constants;
import com.bp.common.core.text.Convert;
import com.bp.common.exception.CustomException;
import com.bp.common.utils.StringUtils;
import com.bp.framework.config.ServerConfig;
import com.bp.framework.util.SecurityUtils;
import com.bp.system.domain.SysFileDomain;
import com.bp.system.service.ISysDictDataService;
import com.bp.system.service.ISysFileService;
import com.bp.system.service.ISysUserService;
import com.bp.village.enums.EnumProjectStatus;
import org.apache.commons.collections4.CollectionUtils;

import javax.annotation.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bp.common.annotation.Log;
import com.bp.common.core.controller.BaseController;
import com.bp.common.core.domain.AjaxResult;
import com.bp.common.enums.EnumBusinessType;
import com.bp.village.project.domain.BizVillageProject;
import com.bp.village.project.service.IBizVillageProjectService;
import com.bp.common.utils.poi.ExcelUtil;
import com.bp.common.core.page.TableDataInfo;

/**
 * 村级工程管理Controller
 * 
 * @author shaominjie
 * @date 2021-01-25
 */
@RestController
@RequestMapping("/village/project")
public class BizVillageProjectController extends BaseController {
    @Resource
    private IBizVillageProjectService bizVillageProjectService;
    @Resource
    private ISysFileService fileService;
    @Resource
    private ISysUserService userService;
    @Resource
    private ISysDictDataService dictDataService;
    @Resource
    private ServerConfig serverConfig;

    /**
     * 查询村级工程管理列表
     */
//    @PreAuthorize("@ss.hasPermi('village:villageProject:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizVillageProject bizVillageProject) {
        startPage();
        List<BizVillageProject> list = bizVillageProjectService.selectList(bizVillageProject);
        return getDataTable(list);
    }

    /**
     * 导出村级工程管理列表
     */
//    @PreAuthorize("@ss.hasPermi('village:villageProject:export')")
    @Log(title = "村级工程管理", businessType = EnumBusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(BizVillageProject bizVillageProject) {
        List<BizVillageProject> list = bizVillageProjectService.selectList(bizVillageProject);
//        dictDataService.selectDictDataByType()
        //数据处理
        if(CollectionUtils.isNotEmpty(list)){
            for(BizVillageProject item : list){
                item.setCurrentStageName(EnumProjectStatus.PROJECT_STATUS_MAP.get(item.getCurrentStage()));
//                item.setProjectTypeName();
            }
        }
        ExcelUtil<BizVillageProject> util = new ExcelUtil<BizVillageProject>(BizVillageProject.class);
        return util.exportExcel(list, "villageProject");
    }

    /**
     * 获取村级工程管理详细信息
     */
//    @PreAuthorize("@ss.hasPermi('village:villageProject:query')")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable("projectId") Long projectId) {
        BizVillageProject project = bizVillageProjectService.selectById(projectId);

        if(project != null && project.getProjectId() != null) {
            // 获取文件的id集合
            StringBuilder fileIdsStr = new StringBuilder();
            Long[] projectFileIds ={};
            List<AjaxResult> projectFiles = new ArrayList<>();
            Long[] meetingFileIds ={};
            List<AjaxResult> meetingFiles= new ArrayList<>();
            Long[] bidContractFileIds ={};
            List<AjaxResult> bidContractFiles= new ArrayList<>();
            Long[] bidReferenceFileIds ={};
            List<AjaxResult> bidReferenceFiles= new ArrayList<>();
            Long[] constructionFileIds ={};
            List<AjaxResult> constructionFiles= new ArrayList<>();
            Long[] auditFileIds ={};
            List<AjaxResult> auditFiles= new ArrayList<>();
            Long[] acceptanceFileIds ={};
            List<AjaxResult> acceptanceFiles= new ArrayList<>();
            if(StringUtils.isNotEmpty(project.getProjectFileIds())){
                fileIdsStr = fileIdsStr.append(project.getProjectFileIds());
                projectFileIds = Convert.toLongArray(project.getProjectFileIds());
            }
            if(StringUtils.isNotEmpty(project.getMeetingFileIds())){
                fileIdsStr = StringUtils.isNotEmpty(fileIdsStr)?fileIdsStr.append(","):fileIdsStr;
                fileIdsStr = fileIdsStr.append(project.getMeetingFileIds());
                meetingFileIds = Convert.toLongArray(project.getMeetingFileIds());
            }
            if(StringUtils.isNotEmpty(project.getBidContractFileIds())){
                fileIdsStr = StringUtils.isNotEmpty(fileIdsStr)?fileIdsStr.append(","):fileIdsStr;
                fileIdsStr = fileIdsStr.append(project.getBidContractFileIds());
                bidContractFileIds = Convert.toLongArray(project.getBidContractFileIds());
            }
            if(StringUtils.isNotEmpty(project.getBidReferenceFileIds())){
                fileIdsStr = StringUtils.isNotEmpty(fileIdsStr)?fileIdsStr.append(","):fileIdsStr;
                fileIdsStr = fileIdsStr.append(project.getBidReferenceFileIds());
                bidReferenceFileIds = Convert.toLongArray(project.getBidReferenceFileIds());
            }
            if(StringUtils.isNotEmpty(project.getConstructionFileIds())){
                fileIdsStr = StringUtils.isNotEmpty(fileIdsStr)?fileIdsStr.append(","):fileIdsStr;
                fileIdsStr = fileIdsStr.append(project.getConstructionFileIds());
                constructionFileIds = Convert.toLongArray(project.getConstructionFileIds());
            }
            if(StringUtils.isNotEmpty(project.getAuditFileIds())){
                fileIdsStr = StringUtils.isNotEmpty(fileIdsStr)?fileIdsStr.append(","):fileIdsStr;
                fileIdsStr = fileIdsStr.append(project.getAuditFileIds());
                auditFileIds = Convert.toLongArray(project.getAuditFileIds());
            }
            if(StringUtils.isNotEmpty(project.getAcceptanceFileIds())){
                fileIdsStr = StringUtils.isNotEmpty(fileIdsStr)?fileIdsStr.append(","):fileIdsStr;
                fileIdsStr = fileIdsStr.append(project.getAcceptanceFileIds());
                acceptanceFileIds = Convert.toLongArray(project.getAcceptanceFileIds());
            }
            List<SysFileDomain> fileDomains = fileService.selectByIds(fileIdsStr.toString());
            if(CollectionUtils.isNotEmpty(fileDomains)){
                for (SysFileDomain item : fileDomains){
                    AjaxResult ajax = AjaxResult.success();
                    ajax.put("fileName", item.getFileName());
//                    ajax.put("url",  serverConfig.getUrl() + Constants.RESOURCE_PREFIX+ item.getFilePath());
                    ajax.put("url",  "http://bpshaomj.biaopunet.com" + Constants.RESOURCE_PREFIX+ item.getFilePath());
                    ajax.put("file", item);
                    if(Arrays.asList(projectFileIds).contains(item.getFileId())){
                        projectFiles.add(ajax);
                    }else if(Arrays.asList(meetingFileIds).contains(item.getFileId())){
                        meetingFiles.add(ajax);
                    }else if(Arrays.asList(bidContractFileIds).contains(item.getFileId())){
                        bidContractFiles.add(ajax);
                    }else if(Arrays.asList(bidReferenceFileIds).contains(item.getFileId())){
                        bidReferenceFiles.add(ajax);
                    }else if(Arrays.asList(constructionFileIds).contains(item.getFileId())){
                        constructionFiles.add(ajax);
                    }else if(Arrays.asList(auditFileIds).contains(item.getFileId())){
                        auditFiles.add(ajax);
                    }else if(Arrays.asList(acceptanceFileIds).contains(item.getFileId())){
                        acceptanceFiles.add(ajax);
                    }
                }
            }
            project.setProjectFiles(projectFiles);
            project.setMeetingFiles(meetingFiles);
            project.setBidContractFiles(bidContractFiles);
            project.setBidReferenceFiles(bidReferenceFiles);
            project.setConstructionFiles(constructionFiles);
            project.setAuditFiles(auditFiles);
            project.setAcceptanceFiles(acceptanceFiles);
        }

        return AjaxResult.success(project);
    }

    /**
     * 新增村级工程管理
     */
//    @PreAuthorize("@ss.hasPermi('village:villageProject:add')")
    @Log(title = "村级工程管理", businessType = EnumBusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizVillageProject bizVillageProject) {
        bizVillageProject.setCreateBy(SecurityUtils.getUsername());
        bizVillageProject.setCreateTime(new Date());
        return toAjax(bizVillageProjectService.insert(bizVillageProject));
    }

    /**
     * 修改村级工程管理
     */
//    @PreAuthorize("@ss.hasPermi('village:villageProject:edit')")
    @Log(title = "村级工程管理", businessType = EnumBusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizVillageProject bizVillageProject) {
        return toAjax(bizVillageProjectService.update(bizVillageProject));
    }

    /**
     * 删除村级工程管理
     */
//    @PreAuthorize("@ss.hasPermi('village:villageProject:remove')")
    @Log(title = "村级工程管理", businessType = EnumBusinessType.DELETE)
	@DeleteMapping("/{projectIds}")
    public AjaxResult remove(@PathVariable Long[] projectIds) {
        return toAjax(bizVillageProjectService.deleteByIds(projectIds));
    }

    @GetMapping(value = "/finish/{projectId}")
    public AjaxResult finish(@PathVariable("projectId") Long projectId){
        BizVillageProject project = bizVillageProjectService.selectById(projectId);
        if(project == null  || project.getProjectId() ==null){
            throw new CustomException("项目异常，请刷新");
        }
        project.setCurrentStage(7);
        project.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(bizVillageProjectService.update(project));
    }
}
